import pandas as pd
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.impute import SimpleImputer


# 读取训练集和测试集数据
train_data = pd.read_csv(r"D:\kaggle\final\cancers-train.csv")
test_data = pd.read_csv(r"D:\kaggle\final\cancers-test.csv")

# 将'Lung_cancer'列的值转换为数值
le = LabelEncoder()
train_data['Lung_cancer'] = le.fit_transform(train_data['Lung_cancer'])

# 分离特征和目标变量
X_train = train_data.drop(['Number', 'Lung_cancer'], axis=1)
y_train = train_data['Lung_cancer']
X_test = test_data.drop(['Number', 'Lung_cancer'], axis=1)

# 创建一个imputer对象，用训练集的平均值填充NaN值
imputer = SimpleImputer(strategy='mean')

# 使用imputer填充训练集和测试集的NaN值
X_train = imputer.fit_transform(X_train)
X_test = imputer.transform(X_test)

# 创建一个scaler对象，用于缩放数据
scaler = StandardScaler()

# 使用scaler缩放训练集和测试集的数据
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 创建并训练模型，增加最大迭代次数
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)

# 预测测试集中的'Lung_cancer'列的概率
test_data['Lung_cancer'] = model.predict_proba(X_test)[:, 1]

# 将预测结果保存到测试集文件中
test_data.to_csv(r"D:\kaggle\final\cancers-test.csv", index=False)